# 窗口操作工具类
import os
import time
import tkinter as tk
import win32gui
import win32process
import win32api
import win32con
import psutil
import pygetwindow as gw
import pyautogui
from utils.logger import logger

def get_screen_size():
    """获取屏幕尺寸"""
    try:
        # 创建临时窗口获取屏幕尺寸
        temp_root = tk.Tk()
        temp_root.withdraw()
        
        screen_width = temp_root.winfo_screenwidth()
        screen_height = temp_root.winfo_screenheight()
        temp_root.destroy()
        
        return screen_width, screen_height
    except Exception as e:
        logger.error(f"获取屏幕尺寸失败: {e}")
        # 返回默认值
        return 1920, 1080


def calculate_window_size(width_percent=0.75, height_percent=0.70, 
                          min_width=500, max_width=1400,
                          min_height=500, max_height=900):
    """
    根据屏幕尺寸计算窗口大小
    
    Args:
        width_percent: 窗口宽度占屏幕宽度的百分比 (0-1)
        height_percent: 窗口高度占屏幕高度的百分比 (0-1)
        min_width: 最小宽度
        max_width: 最大宽度
        min_height: 最小高度
        max_height: 最大高度
    
    Returns:
        (window_width, window_height): 窗口宽度和高度
    """
    screen_width, screen_height = get_screen_size()
    
    # 计算窗口尺寸
    window_width = max(min_width, min(max_width, int(screen_width * width_percent)))
    window_height = max(min_height, min(max_height, int(screen_height * height_percent)))
    
    return window_width, window_height


def get_optimal_window_size():
    """根据屏幕尺寸计算最佳窗口大小（主窗口）"""
    return calculate_window_size(
        width_percent=0.75,
        height_percent=0.70,
        min_width=900,
        max_width=1400,
        min_height=650,
        max_height=900
    )


def center_window(window, width=None, height=None):
    """
    将窗口居中显示
    
    Args:
        window: tkinter窗口对象
        width: 窗口宽度（可选，不提供则使用当前宽度）
        height: 窗口高度（可选，不提供则使用当前高度）
    """
    window.update_idletasks()
    
    if width is None or height is None:
        width = window.winfo_width()
        height = window.winfo_height()
    
    screen_width, screen_height = get_screen_size()
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    
    window.geometry(f'{width}x{height}+{x}+{y}')


class WindowUtils:
    """窗口操作工具类"""    
    
    @staticmethod
    def check_and_set_english_input():
        """检查并设置输入法为英语状态"""
        try:
            # 获取当前线程的输入法
            hwnd = win32gui.GetForegroundWindow()
            thread_id = win32api.GetCurrentThreadId()
            current_ime = win32api.GetKeyboardLayout(thread_id)
            
            # 提取低16位作为语言ID
            lang_id = current_ime & 0xFFFF
            
            # 检查是否为英语输入法 (0x0409 或 0x0809)
            is_english = lang_id in [0x0409, 0x0809]
            
            if not is_english:
                logger.info(f"当前输入法ID: {hex(current_ime)} (语言ID: {hex(lang_id)}), 需要切换到英语输入法")
                
                # 方法1: 使用Ctrl+Shift切换输入法（最可靠）
                for i in range(3):  # 尝试3次
                    pyautogui.hotkey('ctrl', 'shift')
                    time.sleep(0.3)
                    
                    # 检查是否切换成功
                    current_ime = win32api.GetKeyboardLayout(thread_id)
                    lang_id = current_ime & 0xFFFF
                    if lang_id in [0x0409, 0x0809]:
                        logger.info(f"第{i+1}次Ctrl+Shift切换成功，当前语言ID: {hex(lang_id)}")
                        return
                
                # 方法2: 使用Alt+Shift
                logger.info("Ctrl+Shift切换失败，尝试Alt+Shift")
                for i in range(3):
                    pyautogui.hotkey('alt', 'shift')
                    time.sleep(0.3)
                    
                    current_ime = win32api.GetKeyboardLayout(thread_id)
                    lang_id = current_ime & 0xFFFF
                    if lang_id in [0x0409, 0x0809]:
                        logger.info(f"Alt+Shift切换成功，当前语言ID: {hex(lang_id)}")
                        return
                
                # 最终验证
                current_ime = win32api.GetKeyboardLayout(thread_id)
                lang_id = current_ime & 0xFFFF
                if lang_id in [0x0409, 0x0809]:
                    logger.info("输入法切换成功，当前为英语输入法")
                else:
                    logger.warning(f"输入法切换失败，当前语言ID: {hex(lang_id)}")
            else:
                logger.info(f"当前已是英语输入法，语言ID: {hex(lang_id)}")
                
        except Exception as e:
            logger.error(f"输入法检查失败: {e}")
